<?php
/**
 * File: HttpClient.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 14:55
 */

namespace Common\Extend\DingTalk\Client;


use Common\Extend\Helper\Exception;


use Common\Extend\Helper\HttpCurl as Client;

class HttpClient
{
    protected $client;
    protected $token;
    protected $host;
    private static $_instance;


    public function __construct(array $config = [])
    {
        $this->host = $config['host'];
    }

    public static function getInstance($config)
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self($config);
        }
        return self::$_instance;
    }

    public function setToken($token)
    {
        if (!isset($this->token)) {
            $this->token = $token;
        }
    }

    public function clearToken()
    {
        unset($this->token);
    }

    public function get($path, $data)
    {
        $this->client = new Client();
        if (isset($this->token)) {
            $getData = array_merge(['access_token' => $this->token], $data);
        } else {
            $getData = $data;
        }
        $host = $this->host . '/' . $path;
        $response = $this->client
            ->setHeader(['Accept: application/json'])
            ->setParams($getData)
            ->get($host);
        return $this->response($response);

    }

    public function post($path, $data)
    {

    }

    protected function response($response)
    {
        if (!$response) {
            throw new Exception('钉钉api调用失败');
        }
        $data = json_decode($response, true);
        if ($data['errcode'] !== 0) {
            throw new Exception($data['errmsg'], $data['errcode']);
        }
        return $data;
    }


}